<?php

/* JoomLeague League Management and Prediction Game for Joomla!
 * Copyright (C) 2007  Robert Moss
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 

class PowerThumb
{

    /**#@+
    * @acess public
    */
    var $imgSrc;          //  (string)  Image path - absolute or relative to script in execution (the one calling this class)
    var $maxWidth;        //  (int)     Max width allowed
    var $maxHeight;       //  (int)     Max height allowed
    var $imgDescription;  //  (string)  Image description showed in popup
    var $filterType;      //  (string)  Image filter type (applied on thumbs)
    var $filterIntensity; //  (int)     Image filter intensity

    var $imgId;           //  (string)  Id attribute for thumb and ampliation
    var $imgClass;        //  (string)  Class attribute for thumb and ampliation
    var $imgStyle;        //  (array)   Style attribute for thumb and ampliation
    var $imgEvents;       //  (array)   Events attributes for thumb and ampliation

    var $ampliationLink;  //  (bool)    Should create ampliation link? Default: "true" (Set by user)
    /**#@-*/


    /**#@+
    * @acess protected
    */
    var $showThumb;       //  (bool)    Should this script run as thumb generator? Will be "true" when called in tag <img> (Set automatically)
    var $showPopUp;       //  (bool)    Should this script run as a popup? Will be true when called to create the popup HTML code (Set automatically)

    var $class2script;    //  (string)
    var $script2class;    //  (string)
    /**#@-*/


    function PowerThumb($imgSrc = "", $maxWidth = 160, $maxHeight = 120, $imgDescription = "", $imgAlt = "",
                        $imgId = "", $imgClass = "", $imgStyle = array(), $imgEvents = array())
    {
        $this->availableFilters = array('gray', 'red', 'green', 'blue', 'yellow', 'magenta', 'cyan', 'black');

        $this->imgSrc         = (isset($_GET['imgSrc']))          ?  $_GET['imgSrc']          :  $imgSrc;
        $this->maxWidth       = (isset($_GET['maxWidth']))        ?  $_GET['maxWidth']        :  $maxWidth;
        $this->maxHeight      = (isset($_GET['maxHeight']))       ?  $_GET['maxHeight']       :  $maxHeight;
        $this->imgDescription = (isset($_GET['imgDescription']))  ?  $_GET['imgDescription']  :  $imgDescription;
        $this->filterType       = (isset($_GET['filterType']))       ?  $_GET['filterType']       :  "";
        $this->filterIntensity  = (isset($_GET['filterIntensity']))  ?  $_GET['filterIntensity']  :  "";

        $this->imgAlt    = (isset($_GET['imgAlt']))     ?  $_GET['imgAlt']                  :  $imgAlt;
        $this->imgId     = (isset($_GET['imgId']))      ?  $_GET['imgId']                   :  $imgId;
        $this->imgClass  = (isset($_GET['imgClass']))   ?  $_GET['imgClass']                :  $imgClass;
        $this->imgStyle  = (isset($_GET['imgStyle']))   ?  unserialize($_GET['imgStyle'])   :  $imgStyle;
        $this->imgEvents = (isset($_GET['imgEvents']))  ?  unserialize($_GET['imgEvents'])  :  $imgEvents;

        $this->ampliationLink = true;


        $this->showThumb = ((isset($_GET['showThumb']))  &&  ($_GET['showThumb'] == "yes"))  ?  true  :  false;
        $this->showPopUp = ((isset($_GET['showPopUp']))  &&  ($_GET['showPopUp'] == "yes"))  ?  true  :  false;


        // Defines relatives path: script file to class file and class file to script file

        if (isset($_SERVER['SCRIPT_NAME'])) {
            $script_file = realpath(basename($_SERVER['SCRIPT_NAME']));
        } else if (isset($_SERVER['SCRIPT_FILENAME'])) {
            $script_file = realpath(basename($_SERVER['SCRIPT_FILENAME']));
        } else if (isset($_SERVER['PHP_SELF'])) {
            $script_file = realpath(basename($_SERVER['PHP_SELF']));
        } else if (isset($_SERVER['PATH_TRANSLATED'])) {
            $script_file = realpath(basename($_SERVER['PATH_TRANSLATED']));
        } else {
            $script_file = "";
        }

        $class_file = realpath(__FILE__);


        if (isset($_GET['class2script'])) {
            $this->class2script = $_GET['class2script'];
        }
        else {
            $this->class2script = dirname($this->findRelativePath($class_file, $script_file)) . '/';
        }

        $this->script2class = $this->findRelativePath($script_file, $class_file);


        if ($this->showThumb)
        {
            $this->showThumb();
        }

        if ($this->showPopUp)
        {
            $this->showPopUp();
        }
    }


    function setSrc($imgSrc) {
        $this->imgSrc = $imgSrc;
    }

    function setMaxWidth($maxWidth) {
        $this->maxWidth = $maxWidth;
    }

    function setMaxHeight($maxHeight) {
        $this->maxHeight = $maxHeight;
    }

    function setDescription($imgDescription) {
        $this->imgDescription = $imgDescription;
    }

    function setAlt($imgAlt) {
        $this->imgAlt = $imgAlt;
    }

    function setId($imgId) {
        $this->imgId = $imgId;
    }

    function setClass($imgClass) {
        $this->imgClass = $imgClass;
    }

    function setStyle($property, $value) {
        $this->imgStyle[$property] = $value;
    }

    function setEvent($event, $execution) {
        $this->imgEvents[$event] = $execution;
    }

    function setAmpliationLink($boolAmpliationLink) {
        $this->ampliationLink = $boolAmpliationLink;
    }

    function setFilter($type, $intensity = 50) {
        if (!in_array(trim($type), $this->availableFilters)) {
            return false;
        }

        $this->filterType      = trim($type);
        $this->filterIntensity = (int)(max(  min($intensity, 100),  0)); // sets intensity between 0 and 100
    }


    function returnStyle($arrayStyle) {
        $style = array();
        foreach ($arrayStyle as $property => $value) {
            $style[] = $property . ": " . $value . ";";
        }
        return implode(" ", $style);
    }

    function returnEvents($arrayEvents) {
        $events = array();
        foreach ($arrayEvents as $event => $execution) {
            $events[] = ' ' . $event . '="' . $execution . '"';
        }
        return implode(" ", $events);
    }




    function create($imgSrc = "", $shouldPrint = true)
    {
        if ($imgSrc != "")
        {
            $this->imgSrc = $imgSrc;
        }


        $html = "";


        if (($this->ampliationLink == true)  &&  (file($this->imgSrc)))
        {
            $imgSize     = @getimagesize($this->imgSrc);
            $popUpWidth  = ($imgSize[0] + 60);
            $popUpHeight = ($imgSize[1] + 120);
            $scrollbars  = "no";

            if ($popUpWidth > 750)
            {
                $popUpWidth   = 750;
                $popUpHeight += 20;
                $scrollbars   = "yes";
            }
            if ($popUpHeight > 550)
            {
                $popUpWidth  += 20;
                $popUpHeight  = 550;
                $scrollbars   = "yes";
            }


            $queryString  = '?showPopUp=yes&amp;imgSrc=' . urlencode($this->imgSrc);
            $queryString .= '&amp;class2script=' . urlencode($this->class2script);
            $queryString .= '&amp;imgDescription=' . urlencode($this->imgDescription) . '&amp;imgAlt=' . urlencode($this->imgAlt);
            $queryString .= '&amp;imgId=' . urlencode($this->imgId) . '&amp;imgClass=' . urlencode($this->imgId);
            $queryString .= '&amp;imgStyle=' . urlencode(serialize($this->imgStyle));
            $queryString .= '&amp;imgEvents=' . urlencode(serialize($this->imgEvents));

            $html .= "\n\n".'<a href="javascript:;" onclick="javascript: window.open(\'' . $this->script2class . $queryString . "', '', ";
            $html .= '\'scrollbars=' . $scrollbars . ', width=' . $popUpWidth . ', height=' . $popUpHeight . ', left=20, top=20\')">';
        }


        $imgAlt    = ' alt="' . $this->imgAlt . '"';
        $imgId     = ($this->imgId != "")           ?  (' id="' . $this->imgId . '"')                            :  ("");
        $imgClass  = ($this->imgClass != "")        ?  (' class="' . $this->imgClass . '"')                      :  ("");
        $imgStyle  = (count($this->imgStyle) > 0)   ?  (' style="' . $this->returnStyle($this->imgStyle) . '"')  :  ("");
        $imgEvents = (count($this->imgEvents) > 0)  ?  ($this->returnEvents($this->imgEvents))                   :  ("");


        $html .= "\n".'<img src="' . $this->script2class . '?showThumb=yes&amp;imgSrc=' . urlencode($this->imgSrc);
        $html .= '&amp;class2script=' . urlencode($this->class2script);
        $html .= '&amp;maxWidth=' . $this->maxWidth . '&amp;maxHeight=' . $this->maxHeight;
        $html .= '&amp;filterType=' . $this->filterType . '&amp;filterIntensity=' . $this->filterIntensity . '" ';
        $html .= $imgAlt . $imgId . $imgClass . $imgStyle . $imgEvents . ' />';

        if ($this->ampliationLink == true)
        {
            $html .= "\n</a>\n";
        }



        if ($shouldPrint == true) {
            echo $html;
        } else {
            return $html;
        }
    }



    /**
    * Author: Carlos Reche
    * based on Mauricio Wolff and Michael Bailey's work
    *
    * @Nov 25, 2004
    */
    function showThumb()
    {
        $this->img = "";

        if (!preg_match("/^https?:\\/\\//i", $this->imgSrc))
        {
            $this->imgSrc = $this->class2script . $this->imgSrc;
        }


        if (file($this->imgSrc))
        {
            $imgInfo = getimagesize($this->imgSrc);

            if (preg_match("/^image\/(pjpeg|jpeg)$/", $imgInfo['mime'])) {
                $this->img = @imagecreatefromjpeg($this->imgSrc);
            }
            else if (preg_match("/^image\/gif$/", $imgInfo['mime'])) {
                $this->img = @imagecreatefromgif($this->imgSrc);
            }
            else if (preg_match("/^image\/png$/", $imgInfo['mime'])) {
                $this->img = @imagecreatefrompng($this->imgSrc);
            }
        }


        // Verifies if image was loaded
        if ($this->img)
        {
            // Gets image size and resize scale
            $width  = $newWidth  = $imgInfo[0];
            $height = $newHeight = $imgInfo[1];
            $scale  = min(($this->maxWidth/$width), ($this->maxHeight/$height));


            if ($scale < 1  ||  $this->filterType != "")
            {
                if ($scale < 1) {
                    $newWidth  = floor($scale * $width);
                    $newHeight = floor($scale * $height);
                }


                if (function_exists("imagecreatetruecolor")  &&  $this->filterType == "") {
                    $tempImg = imagecreatetruecolor($newWidth, $newHeight);
                }
                else {
                    $tempImg = imagecreate($newWidth, $newHeight);
                }


                $this->applyFilter($tempImg);


                // Copies and resizes the old image into the new one
                imagecopyresampled($tempImg, $this->img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                imagedestroy($this->img);
                $this->img = $tempImg;
            }
        }

        else
        {
            // If couldn't load image, creates an error image

            $this->img = imagecreate($this->maxWidth, $this->maxHeight);

            $lightgray = imagecolorallocate($this->img, 230, 230, 230);
            $gray      = imagecolorallocate($this->img, 153, 153, 153);
            $black     = imagecolorallocate($this->img, 0, 0, 0);

            imagefill($this->img, 0, 0, $lightgray);
            imagerectangle($this->img, 8, 8, 30, 30, $gray);
            imagerectangle($this->img, 6, 6, 32, 32, $gray);
            imageline($this->img, 12, 12, 26, 26, $gray);
            imageline($this->img, 12, 26, 26, 12, $gray);
 //           imagestring($this->img, 3, 40, 5, 'Image not', $black );
 //           imagestring($this->img, 3, 40, 20, 'found', $black );
        }

        header('Content-type: image/jpeg');
        imagejpeg($this->img);
    }



    /**
    * Author: Carlos Reche
    * based on Alfred Reinold Baudisch's work
    *
    * @Nov 25, 2004
    */
    function applyFilter(&$img)
    {
        $intensity = (100 - $this->filterIntensity) / 100;

        switch ($this->filterType)
        {
            case "gray":
                for ($c = 0; $c < 256; $c++) {
                    imagecolorallocate($img, $c, $c, $c);
                }
                break;

            case "red":
                for ($full = $less = 0; $full < 256; $full++, $less = floor($full * $intensity))
                {
                    imagecolorallocate($img, $full, $less, $less);
                }
                break;

            case "green":
                for ($full = $less = 0; $full < 256; $full++, $less = floor($full * $intensity))
                {
                    imagecolorallocate($img, $less, $full, $less);
                }
                break;

            case "blue":
                for ($full = $less = 0; $full < 256; $full++, $less = floor($full * $intensity))
                {
                    imagecolorallocate($img, $less, $less, $full);
                }
                break;

            case "yellow":
                for ($full = $less = 0; $full < 256; $full++, $less = floor($full * $intensity))
                {
                    imagecolorallocate($img, $full, $full, $less);
                }
                break;

            case "magenta":
                for ($full = $less = 0; $full < 256; $full++, $less = floor($full * $intensity))
                {
                    imagecolorallocate($img, $full, $less, $full);
                }
                break;

            case "cyan":
                for ($full = $less = 0; $full < 256; $full++, $less = floor($full * $intensity))
                {
                    imagecolorallocate($img, $less, $full, $full);
                }
                break;

            case "black":
                for ($full = $less = 0; $full < 256; $full++, $less = floor($full * $intensity))
                {
                    imagecolorallocate($img, $less, $less, $less);
                }
                break;
        }
    }





    function showPopUp()
    {
        if (!preg_match("/^https?:\\/\\//i", $this->imgSrc))
        {
            $this->imgSrc = $this->class2script . $this->imgSrc;
        }


        if (!isset($this->imgStyle['border'])) { $this->setStyle("border", "1px solid #000000"); }

        $imgAlt    = ' alt="' . $this->imgAlt . '"';
        $imgId     = ($this->imgId != "")           ?  (' id="' . $this->imgId . '"')                            :  ("");
        $imgClass  = ($this->imgClass != "")        ?  (' class="' . $this->imgClass . '"')                      :  ("");
        $imgStyle  = (count($this->imgStyle) > 0)   ?  (' style="' . $this->returnStyle($this->imgStyle) . '"')  :  ("");
        $imgEvents = (count($this->imgEvents) > 0)  ?  ($this->returnEvents($this->imgEvents))                   :  ("");


        $html  = '<?xml version="1.0" encoding="ISO-8859-1" ?>';
        $html .= "\n".'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
        $html .= "\n".'<html xmlns="http://www.w3.org/1999/xhtml">';
        $html .= "\n<head>\n\n<title>" . $this->imgDescription . "</title>\n\n";
        $html .= "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n";
        $html .= "\n".'<style type="text/css">';
        $html .= "\n  body { background-color: #ffffff; text-align: center; font-family: Verdana, Arial; font-size: 15px; font-weight: bold; color: #cc7700; }";
        $html .= "\n  a:link    { color: #0000cc; text-decoration: none; }";
        $html .= "\n  a:visited { color: #0000cc; text-decoration: none; }";
        $html .= "\n  a:hover   { color: #6666cc; }";
        $html .= "\n  a:active  { color: #cc0000; }";
        $html .= "\n".'</style>';
        $html .= "\n</head>\n\n";

        $html .= "\n<body>\n\n";
        $html .= '<img src="' . $this->imgSrc . '"' . $imgAlt . $imgId . $imgClass . $imgStyle . $imgEvents . ' />';
        $html .= "\n".'<div style="margin: 15px auto;">';
        $html .= "\n".'  <span style="font-style: italic;">' . $this->imgDescription . '</span>';
        $html .= "\n".'  <div style="clear: both; padding-top: 20px;">';
        $html .= "\n".'    <a href="javascript: parent.window.opener=self; parent.window.close();">'._JL_POPUP_CLOSE.'.</a>';
        $html .= "\n".'  </div>';
        $html .= "\n".'</div>';
        $html .= "\n\n</body>\n</html>\n";

        echo $html;
    }


    function fixPath($path)
    {
        if ($path == "")
        {
            return false;
        }

        $path = trim(preg_replace("/\\\\/", "/", (string)$path));

        if (!preg_match("/(\.\w{1,4})$/", $path)  &&  !preg_match("/\?[^\\/]+$/", $path)  &&  !preg_match("/\\/$/", $path))
        {
            $path .= '/';
        }

        preg_match_all("/^(\\/|\w:\\/|(http|ftp)s?:\\/\\/[^\\/]+\\/)?(.*)$/i", $path, $matches, PREG_SET_ORDER);

        $path_root = $matches[0][1];
        $path_dir  = $matches[0][3];

        $path_dir = preg_replace(  array("/^\\/+/", "/\\/+/"),  array("", "/"),  $path_dir  );

        $path_parts = explode("/", $path_dir);

        for ($i = 0, $real_path_parts = array(); $i < count($path_parts); $i++)
        {
            if ($path_parts[$i] == '.')
            {
                continue;
            }
            else if ($path_parts[$i] == '..')
            {
                if (  (isset($real_path_parts[0])  &&  $real_path_parts[0] != '..')  ||  ($path_root != "")  )
                {
                    array_pop($real_path_parts);
                    continue;
                }
            }

            array_push($real_path_parts, $path_parts[$i]);
        }

        return $path_root . implode("/", $real_path_parts);
    }




    function findRelativePath($path_1, $path_2)
    {
        if ($path_1 == ""  ||  $path_2 == "")
        {
            return false;
        }

        $path_1 = $this->fixPath($path_1);
        $path_2 = $this->fixPath($path_2);

        preg_match_all("/^(\\/|\w:\\/|https?:\\/\\/[^\\/]+\\/)?(.*)$/i", $path_1, $matches_1, PREG_SET_ORDER);
        preg_match_all("/^(\\/|\w:\\/|https?:\\/\\/[^\\/]+\\/)?(.*)$/i", $path_2, $matches_2, PREG_SET_ORDER);

        if ($matches_1[0][1] != $matches_2[0][1])
        {
            return false;
        }

        $path_1_parts = explode("/", $matches_1[0][2]);
        $path_2_parts = explode("/", $matches_2[0][2]);


        while (isset($path_1_parts[0])  &&  isset($path_2_parts[0]))
        {
            if ($path_1_parts[0] != $path_2_parts[0])
            {
                break;
            }

            array_shift($path_1_parts);
            array_shift($path_2_parts);
        }


        for ($i = 0, $path = ""; $i < count($path_1_parts)-1; $i++)
        {
            $path .= "../";
        }

        return $path . implode("/", $path_2_parts);
    }


}





// Starts the class - used when this file is called in <img> tag and on popup HTML code generation
$GO = new PowerThumb();




?>
